package com.ross.mode.three;

import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @version 1.0.0
 * @className: Proxy
 * @description: 代理类
 * @author: zhangjunfa
 * @date: 2023/8/29 13:22
 */
@Slf4j
public class ProxyInterceptor implements MethodInterceptor {
    /**
     * 目标对象
     */
    private UserService target;

    /**
     * 事务控制
     */
    private MapperTransactional transactional;

    /**
     * 构造器
     *
     * @param target
     */
    public ProxyInterceptor(UserService target, MapperTransactional transactional) {
        this.target = target;
        this.transactional = transactional;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        transactional.before(o, method, args, methodProxy);
        Object result = method.invoke(target, args);
        transactional.after(o, method, args, methodProxy);
        return result;
    }

    //返回一个代理对象:  是 target 对象的代理对象
    public Object getProxyInstance() {
        //1. 创建一个工具类
        Enhancer enhancer = new Enhancer();
        //2. 设置父类
        enhancer.setSuperclass(target.getClass());
        //3. 设置回调函数
        enhancer.setCallback(this);
        //4. 创建子类对象，即代理对象
        return enhancer.create();
    }
}
